<template>
  <!-- 生产BOM表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      title="复制BOM"
      width="1000px"
      draggable
      @close="closeDialog"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :inline="true"
        :rules="rules"
        label-width="160"
      >
        <div class="search-container">
          <el-form :model="searchParam" :inline="true">
            <el-form-item label="工厂">
              <el-select
                @change="changePlant"
                v-model="searchParam.plantId"
                placeholder="请选择工厂"
                style="width: 100%"
                clearable
              >
                <el-option
                  v-for="item in plants"
                  :key="item.id"
                  :label="item.organizationName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="成品物料">
              <el-input
                v-model="searchParam.materialCode"
                placeholder="请选择成品物料"
                :disabled="!searchParam.plantId"
                clearable
                readonly
                @click="showWorkOrderSelect"
              >
                <template #append>
                  <el-button
                    type="success"
                    :disabled="!searchParam.plantId"
                    plain
                    @click="showWorkOrderSelect"
                    >选择</el-button
                  >
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="BOM编号">
              <el-input
                v-model="searchParam.bomCode"
                placeholder="请输入BOM编号"
                clearable
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="search"
                ><i-ep-search />搜索</el-button
              >
              <el-button @click="reset"><i-ep-refresh />重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-card shadow="never" class="table-container">
          <el-table
            ref="bomSelectTableRef"
            v-loading="tableLoading"
            :data="tableData"
            highlight-current-row
            @selection-change="handleSelectionChange"
            row-key="id"
            border
            :tree-props="{ children: 'nodes', hasChildren: 'hasChildren' }"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column
              label="物料"
              prop="materialCode"
              min-width="100"
              show-overflow-tooltip
              align="left"
            />
            <el-table-column
              label="数量"
              prop="matQuantity"
              min-width="100"
              show-overflow-tooltip
              align="center"
            >
              <template #default="scope">
                {{ scope.row.baseQuantity }}
                {{
                  useDictionary("MeasurementUnit", scope.row.baseQuantityUnit)
                }}
              </template>
            </el-table-column>
            <el-table-column
              label="工厂"
              prop="plantName"
              min-width="100"
              show-overflow-tooltip
              align="center"
            />
            <el-table-column
              label="BOM编号"
              prop="bomCode"
              min-width="100"
              show-overflow-tooltip
              align="center"
            />
            <el-table-column
              label="BOM描述"
              prop="bomDescription"
              min-width="100"
              show-overflow-tooltip
            />
          </el-table>
          <el-pagination
            :background="true"
            :current-page="pageable.pageNum"
            :page-size="pageable.pageSize"
            :page-sizes="[10, 25, 50, 100]"
            :total="pageable.total"
            layout="total, sizes, prev, pager, next, jumper"
            class="mt-[20px]"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-card>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            :disabled="ids.length === 0"
            :loading="loading"
            @click="handleSubmit"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <conten-select
      :visible="selectDialogSELECT.visible"
      @change-visible="changeVisibleSELECT"
      :plantId="searchParam.plantId"
      :brekList="brekList"
    />
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictionary, useDownload, useTable } from "@/utils/useTable";

defineOptions({
  name: "MESMESBOMDETAILCOPY",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);
const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  ids: {
    type: Array,
    default: () => {
      return [];
    },
  },
});

// 请求参数
const requestApi = "/mes/mesbom/queryByPage";

// 是否需要分页
const pagination = true;

const initParam = {};

// 初始化搜索参数数据
const searchParamInit = {
  bomCode: "",
  plantId: "",
  materialCode: "",
};

const deleteParam = {
  api: "/mes/mesbom/delete",
  data: {},
};

// 数据请求错误后处理
function requestError() {}

const bomSelectTableRef = ref(null);

const dataCallBack = ref(undefined); // 无需二次数据处理&不传赞数也行

// 表格操作 Hooks
const {
  tableData,
  pageable,
  searchParam,
  getTableList,
  search,
  ids,
  reset,
  handleSizeChange,
  handleCurrentChange,
  loading: tableLoading,
}: any = useTable(
  requestApi,
  initParam,
  searchParamInit,
  pagination,
  dataCallBack.value,
  requestError,
  deleteParam
);

const changePlant = (val) => {
  if (!val) return;
  searchParam.value.materialId = "";
  searchParam.value.materialCode = "";
};
const plants = ref([]);
const getPlants = async () => {
  const data = await request({
    url: "/system/sysOrganization/getList",
    method: "post",
    data: { organizationType: 3 },
  });
  plants.value = data.data;
};

//选择物料弹窗
const selectDialogSELECT = ref({
  visible: false,
});
const changeVisibleSELECT = (val: boolean, data: any) => {
  selectDialogSELECT.value.visible = val;
  if (data) {
    searchParam.value.materialId = data.id;
    searchParam.value.materialCode = data.materialCode;
  }
};
// 回显的数据
const brekList = ref([]);
const showWorkOrderSelect = () => {
  selectDialogSELECT.value.visible = true;
};

const handleSelectionChange = (list: any) => {
  ids.value = [];
  if (list.length > 1) {
    bomSelectTableRef.value.clearSelection();
    bomSelectTableRef.value.toggleRowSelection(list[list.length - 1]);
  }
  if (list[list.length - 1]?.id) ids.value = [list[list.length - 1]?.id];
};

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  async (newVal: boolean) => {
    // await getBomList();
    getTableList();
    visibleDialog.value = newVal;
    formData.ids = props.ids;
    await getPlants();
    setTimeout(() => {
      formRef.value.clearValidate();
    }, 50);
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  bomId: "",
  parentId: "",
  ids: [],
});
/** rules规则 */
const rules = reactive({
  bomId: [{ required: true, message: "请选择BOM", trigger: "blur" }],
});

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
  Object.assign(searchParam, searchParamInit);
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.bomId = "";
  formData.ids = [];
}

const loading = ref(false);

/** 生产BOM保存提交 */
async function handleSubmit() {
  if (ids.value.length === 0)
    return ElMessage.warning("请选择要复制的BOM");
  loading.value = true;
  formData.bomId = ids.value[0];
  await request({
    url: "/mes/mesbom/copy",
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  ElMessage.success(`复制成功`);
  closeDialog();
  emit("reset-table", formData);
}
</script>
